#!/bin/bash

# mkatag is part of code.google.com/camtools, copyright 2008, 2009 Camille Huot
# and is licensed under http://www.gnu.org/copyleft/gpl.html

# mkatag is a tool to tag a MKA (Matroska Audio) file.
# It can be helped by an optional CUE file.

# please see http://www.cameuh.net/pmwiki.php/Docs/MatroskaAudio
# for usage instruction.

cue=""

[ $# -lt 1 ] && {
 echo "mkatag -- http://www.cameuh.net/pmwiki.php/Docs/MatroskaAudio"
 echo "Usage: mkatag <album.mka> -cue=<album.cue>"
 echo " will create and merge XML tags from album.cue and your answers"
 exit
}
while [ $# -gt 0 ]; do
 a="$1"
 if echo $a | grep -q "^-cue=."; then
  cue=$(echo $a | sed 's/^-cue=//')
 else
  mka="$1"
 fi
 shift
done

[ -r "$mka" ] || {
 echo "Fatal: $mka isn't readable!"
 exit 1
}

[ -w "$mka" ] || {
 echo "Warning: $mka isn't writable, mkatag won't alter it."
}

tmp="/tmp/mkatag.$$.tmp"
rm -f "$tmp" || {
 echo "Unable to create a temp (in /tmp/) file..."
 exit 1
}

# let's read the MKA and extract the chapter list
mkvinfo "$mka" | \
 egrep '(Track number|\|   \+ ChapterUID:)' | cut -d: -f 2 | \
 sed 's/^ *//;s/ *$//' > "$tmp"
nb=$(($(wc -l "$tmp" | awk '{ print $1 }')-1))
if [ $nb -gt 0 ]; then
 echo "$nb chapters found."
else
 echo "I can't find any chapters!"
 exit 1
fi


performer=""
title=""

# let's read the CUE if supplied
[ -r "$cue" ] && {
 tracks=0
 while read line; do
  if echo $line | grep -q "PERFORMER"; then
   [ -z "$performer" ] && performer="$(echo $(echo $line | cut -d'"' -f2))"
  elif echo $line | grep -q "REM GENRE"; then
   [ -z "$genre" ] && genre="$(echo $(echo $line | cut -d'"' -f2))"
  elif echo $line | grep -q "REM DATE"; then
   [ -z "$year" ] && year="$(echo $line | sed 's/[^0-9]*//g')"
  elif echo $line | grep -q "TITLE"; then
   if [ "$tracks" -eq 0 ]; then
    title="$(echo $(echo $line | cut -d'"' -f2))"
   else
    eval $(echo "export title_$(echo $tracks)=\"$(echo $(echo "$line" | cut -d'"' -f2))\"")
   fi
  elif echo $line | grep -q "TRACK"; then
   tracks=$(echo $line | awk '{ print $2 }' | sed 's/^0*//')
  fi
 done < "$cue"
}

# now we ask to manually confirm each value
confirm () {
 [ $# -ne 2 ] && { echo "confirm: bad arg count"; exit; }
 echo -n "$1 [$(eval echo \$$2)]: "
 read a
 [ -n "${a}" ] && eval $2=\"$a\"
}

confirm "Artist name" performer
confirm "Album name" title
confirm "Production year" year
confirm "Genre" genre
confirm "Country (2-letter ISO code)" country
i=1; while [ $i -le $nb ]; do
 confirm "Track #${i} name" title_$i
 let i=$i+1
done

xml() {
 echo $* | sed 's/</&lt;/g;s/&/&amp;/g'
}

# OK, now we write the xml
xml="/tmp/mkatag.$$.xml"
rm -f "$xml"
cat > "$xml" <<EOF
<Tags>
<Tag>
<Targets>
 <TargetType>ALBUM</TargetType>
 <TargetTypeValue>50</TargetTypeValue>
</Targets>
<Simple>
 <Name>ARTIST</Name>
 <String>$(xml $performer)</String>
</Simple>
<Simple>
 <Name>TITLE</Name>
 <String>$(xml $title)</String>
</Simple>
<Simple>
 <Name>DATE_RELEASED</Name>
 <String>$(xml $year)</String>
</Simple>
<Simple>
 <Name>GENRE</Name>
 <String>$(xml $genre)</String>
</Simple>
<Simple>
 <Name>COMPOSER_NATIONALITY</Name>
 <String>$(xml $country)</String>
</Simple>
<Simple>
 <Name>COMMENT</Name>
 <String>Tagged by [cam]</String>
</Simple>
<Simple>
 <Name>TOTAL_PARTS</Name>
 <String>1</String>
</Simple>
</Tag>

<Tag>
<Targets>
 <TargetType>PART</TargetType>
 <TargetTypeValue>40</TargetTypeValue>
</Targets>
<Simple>
 <Name>PART_NUMBER</Name>
 <String>1</String>
</Simple>
<Simple>
 <Name>TOTAL_PARTS</Name>
 <String>$nb</String>
</Simple>
</Tag>
EOF

i=1
cat "$tmp" | sed '1d' | while read chapuid; do
 title=$(eval "echo \$title_${i}")
 cat >> "$xml" <<EOF
<Tag>
<Targets>
 <ChapterUID>$chapuid</ChapterUID>
 <TargetType>TRACK</TargetType>
 <TargetTypeValue>30</TargetTypeValue>
</Targets>
<Simple>
 <Name>PART_NUMBER</Name>
 <String>$i</String>
</Simple>
<Simple>
 <Name>TITLE</Name>
 <String>$(xml $title)</String>
</Simple>
</Tag>
EOF
 let i=$i+1
done

echo "</Tags>" >> "$xml"

echo "Merging the tags into the matroska"
mkvmerge -o "$mka".tag --tags 1:"$xml" "$mka" || {
 echo "Failed! Tags are saved in $xml"
 exit 1
}

echo "Replacing the old file by the new one"
mv -iv "$mka".tag "$mka"
